package com.cy.mall.service.comm.impl;

import java.security.Signature;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.model.Result;
import com.cy.mall.model.dto.bigdata.BigDataCheckParamDTO;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.comm.BigDataService;

import lombok.extern.slf4j.Slf4j;

/**
 * 大数据查询服务
 *
 * @author tanyilin
 *
 * @create 2019年2月28日 下午2:57:35
 */
@Slf4j
@Service
public class BigDataServiceImpl extends BaseService implements BigDataService {
	
	/** md5加密串前缀 6tj4u */
	private String signPre = "6tj4u";
	
	@Value("${big-data.query.url}")
	private String queryUrl;
	
	@Value("${big-data.query.app-code}")
	private String appCode;
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Override
	public Result check(BigDataCheckParamDTO paramDTO) {
		
		//参数
		Map<String, String> params = new HashMap<>();
		params.put("idCard", paramDTO.getIdCard());
		params.put("mobile", paramDTO.getMobile());
		params.put("name", paramDTO.getName());
		params.put("sign", CommonUtils.md5(signPre.concat(CommonUtils.dateFormat3(new Date()))));
		//请求头
		HttpHeaders headers = new HttpHeaders();
		headers.add("Authorization", "APPCODE ".concat(appCode));
		headers.add("Content-Type", "application/json; charset=UTF-8");
		HttpEntity httpEntity = new HttpEntity(null, headers);
		
		log.info("客户大数据查询，参数 params = {}", params);
		
		ResponseEntity<String> responseEntity = restTemplate.exchange(getUrl(queryUrl, params), HttpMethod.POST, httpEntity, String.class);
		
		if(!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
			return Result.fail("请求 查询客户大数据结果  API 失败");
		}
		
		log.info("客户大数据查询，回调报文 = {}", responseEntity.getBody());
		
		Map<String, Object> bodyMap = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
		
		Object rc = bodyMap.get("rc");
		if(!"0000".equals(rc)) {
			return Result.fail("客户大数据结果查询失败，原因=" + (bodyMap.get("msg")));
		}
		
		return Result.success("客户大数据结果查询成功", bodyMap);
	}

	private String getUrl(String url, Map<String, String> params) {
		StringBuilder queryUrl = new StringBuilder(url);
		queryUrl.append("?");
		
		for(String k : params.keySet()) {
			queryUrl.append(k).append("=").append(params.get(k)).append("&");
		}
		
		return queryUrl.toString().substring(0, queryUrl.length() - 1);
		
	}

	@Override
	public Result<Map<String, Object>> postForm() {
		
		String url = "http://localhost:8090/home/post/form";
		
		MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
		body.add("name", "小明");
		body.add("mobile", "13200132001");
		body.add("age", "18");
    	
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    	HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(body, headers);
    	
    	ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
    	
    	log.info("测试 RestTemplate post form 参数，回调报文={}", responseEntity.getBody());
    	
    	Map<String, Object> map = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
    	
		
		return Result.success("", map);
	}

	@Override
	public Result<Map<String, Object>> postJson() {
		
		String url = "http://localhost:8090/home/post/json";
		
		Map<String, String> params = new HashMap<>();
		params.put("name", "小明");
		params.put("mobile", "13200132001");
		params.put("ageageageage", "18");
    	
    	String paramsJson = JsonObjectMapper.toJson(params);
    	
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        
        HttpEntity<String> httpEntity = new HttpEntity(paramsJson, headers);
        
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
//        HttpEntity<String> httpEntity = new HttpEntity<String>(paramsJson, headers);
//        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        
        log.info("测试 RestTemplate post Json 参数，回调报文={}", responseEntity.getBody());
    	
    	Map<String, Object> map = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
    	
		
		return Result.success("", map);
	}

}
